#include <S32FILE.H>

#include "Logger.h"

#ifdef LogEnabled

_LIT(KDebugFileName, "c:\\data\\mrlock_log.txt");

void Logger::Clear()
{
//delete the log.txt file
	RFileWriteStream wStream;
	RFs fs;
	if (KErrNone == fs.Connect())
	{
		if (KErrNone == wStream.Replace(fs, KDebugFileName, EFileWrite))
			wStream.Close();
		fs.Close();
	}
}
//do not use cleanup stack, because AddLineF functions can be called from destructors!
void Logger::AddLineF(TRefByValue<const TDesC8> aFormat, ...)
{
	VA_LIST list;
	VA_START(list, aFormat);
	AddLineF(aFormat,list);
}

void Logger::AddLineF(TRefByValue<const TDesC8> aFormat, VA_LIST aList)
{
	RFs fs;
	if (KErrNone != fs.Connect())
		return ;

	TEntry entry;
	if (KErrNone == fs.Entry(KDebugFileName, entry))
	{
		if (entry.iSize > 100000)
		{
			fs.Delete(KDebugFileName);
		}
	}	

	RFileWriteStream stream;
//open the stream	
	if (KErrNone != stream.Open(fs, KDebugFileName, EFileWrite | EFileShareAny))
	{//file does not exists, create it
		if (KErrNone != stream.Replace(fs, KDebugFileName, EFileWrite | EFileShareAny))
			return ;
	}
	stream.Sink()->SeekL(MStreamBuf::EWrite, EStreamEnd, 0);//end of stream
	
//format the time
	TTime now;
	now.HomeTime();
	TBuf<100> timeBuf;
	now.FormatL(timeBuf, _L("%F%Y%M%D:%H%T%S"));
 
	TBuf8<1400>* buf = new (ELeave) TBuf8<1400>;
	buf->Copy(timeBuf);
	buf->Append(_L8(" : "));	
	buf->AppendFormatList(aFormat, aList);
	buf->Append(_L8("\r\n"));	
	stream.WriteL(*buf);
	stream.Close();
	fs.Close();
	delete buf;
}

//do not use cleanup stack, because AddLineF functions can be called from destructors!
void Logger::AddLineF(TRefByValue<const TDesC> aFormat, ...)
{
	VA_LIST list;
	VA_START(list, aFormat);
	AddLineF(aFormat,list);
}

void Logger::AddLineF(TRefByValue<const TDesC> aFormat, VA_LIST aList)
{
	RFs fs;
	if (KErrNone != fs.Connect())
		return ;
	RFileWriteStream stream;
//open the stream	
	if (KErrNone != stream.Open(fs, KDebugFileName, EFileWrite | EFileShareAny))
	{//file does not exists, create it
		if (KErrNone != stream.Replace(fs, KDebugFileName, EFileWrite | EFileShareAny))
			return ;
	}
	stream.Sink()->SeekL(MStreamBuf::EWrite, EStreamEnd, 0);//end of stream
	
//format the time
	TTime now;
	now.HomeTime();
	TBuf<100> timeBuf;
	now.FormatL(timeBuf, _L("%F%Y%M%D:%H%T%S"));
 
	TBuf<1400>* buf = new (ELeave) TBuf<1400>;
	buf->Copy(timeBuf);
	buf->Append(_L(" : "));	
	buf->AppendFormatList(aFormat, aList);
	buf->Append(_L("\r\n"));
	TBuf8<1400>* buf8 = new (ELeave) TBuf8<1400>;
	buf8->Copy(*buf);
	delete buf;
	stream.WriteL(*buf8);
	delete buf8;
	stream.Close();
	fs.Close();
}

void Logger::EnterFunction(const TDesC8& aFuncName)
{
	AddLineF(_L8("+%S"), &aFuncName);
}
void Logger::LeaveFunction(const TDesC8& aFuncName)
{
	AddLineF(_L8("-%S"), &aFuncName);
}
#endif
